package reflect;

import reflect.annotations.AutoRunClass;
import reflect.annotations.AutoRunMethod;

import java.io.File;
import java.lang.reflect.Method;

/**
 * 自动调用与Test4在同一个包中那些被@AutoRunClass标注的类中所有被@AutoRunMethod标注的方法
 */
public class Test4 {
    public static void main(String[] args) throws Exception{
        File dir = new File(
                Test4.class.getResource(".").toURI()
        );

        String packageName = Test4.class.getPackage().getName();
        File[] subs = dir.listFiles(f->f.getName().endsWith(".class"));
        for (File sub : subs) {
            String fileName = sub.getName();
            String className = fileName.substring(0,fileName.indexOf("."));
            Class cls = Class.forName(packageName+"."+className);
            if (cls.isAnnotationPresent(AutoRunClass.class)){
                Object obj = cls.newInstance();
                Method[] methods = cls.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AutoRunMethod.class)){
                        method.invoke(obj);
                    }
                }
            }

        }
    }
}
